/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jobportal.student;

import java.sql.*;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import jobportal.Dbconn;

/**
 *
 * @author project
 */
public class StudentLogin extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        try {
            HttpSession session = request.getSession();
            Connection con = Dbconn.getConn();
            RequestDispatcher rd = request.getRequestDispatcher("student.jsp");
            Statement st = con.createStatement();
            ResultSet rs;
            String username, password, sql;
            username = request.getParameter("username");
            password = request.getParameter("password");
            sql = "select username,password,name from student where username='" + username + "'";

            out.println(username + password);

            rs = st.executeQuery(sql);
            if (rs.next()) {
                if (rs.getString("password").equals(password)) {
                    response.setHeader("Cache-Control", "no-cache");
                    response.setHeader("Cache-Control", "no-store");
                    response.setDateHeader("Expires", 0);
                    response.setHeader("Pragma", "no-cache");

                    request.getSession();
                    session.setAttribute("role", "student");
                    session.setAttribute("username", rs.getString("username"));
                    session.setAttribute("name", rs.getString("name"));
                    st.executeUpdate("Update student set lastlogin=now() where username='" + rs.getString("username") + "'");
                    response.sendRedirect("student/home.jsp");
                } else {
                    session.invalidate();
                    request.setAttribute("msg", "<strong><font color=red>Invalid Username or Password</font></strong>");
                    rd.forward(request, response);
                }
            } else {
                session.invalidate();
                request.setAttribute("msg", "<strong><font color=red>Invalid Username or Password</font></strong>");
                rd.forward(request, response);
            }

        } catch (Exception e) {
            out.println("Exception:: " + e);
        }
    }
}
